#pragma once

#include <vector>
#include <pthread.h>
#include <semaphore.h>

static const int gcap = 5;

template<class T>
class RingQueue
{
public:
    RingQueue(const int cap = gcap):_ring(cap), _cap(cap), _p_step(0), _c_step(0)
    {
        sem_init(&_space_sem, 0, _cap);
        sem_init(&_data_sem, 0, 0);

        pthread_mutex_init(&_p_mutex, nullptr);
        pthread_mutex_init(&_c_mutex, nullptr);
    }
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t& sem)
    {
        sem_post(&sem);
    }
    void push(const T& in)
    {
        P(_space_sem);
        pthread_mutex_lock(&_p_mutex);
        _ring[_p_step++] = in;
        _p_step %= _cap;
        pthread_mutex_unlock(&_p_mutex);
        V(_data_sem);
    }
    void pop(T* out)
    {
        P(_data_sem);
        pthread_mutex_lock(&_c_mutex);
        *out = _ring[_c_step++];
        _c_step %= _cap;
        pthread_mutex_unlock(&_c_mutex);
        V(_space_sem);
    }
    ~RingQueue()
    {     
        sem_destroy(&_space_sem);
        sem_destroy(&_data_sem);

        pthread_mutex_destroy(&_p_mutex);
        pthread_mutex_destroy(&_c_mutex);
    }
private:
    std::vector<T> _ring;
    int _cap;
    sem_t _space_sem;
    sem_t _data_sem;
    int _p_step;
    int _c_step;
    pthread_mutex_t _p_mutex;
    pthread_mutex_t _c_mutex;
};